package com.geekai.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geekai.chat.dto.MessageDto;
import com.geekai.chat.entity.Message;
import com.geekai.chat.mapper.MessageMapper;
import com.geekai.chat.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    public Message saveUserMessage(Long conversationId, String content) {
        Message message = new Message();
        message.setConversationId(conversationId);
        message.setRole(Message.Role.USER.getValue());
        message.setContent(content);
        message.setTokens(0);

        save(message);
        return message;
    }

    @Override
    public Message saveAssistantMessage(Long conversationId, String content, String model, Integer tokens) {
        Message message = new Message();
        message.setConversationId(conversationId);
        message.setRole(Message.Role.ASSISTANT.getValue());
        message.setContent(content);
        message.setModel(model);
        message.setTokens(tokens != null ? tokens : 0);

        save(message);
        return message;
    }

    @Override
    public List<MessageDto> getConversationMessages(Long conversationId) {
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", conversationId)
                .orderByAsc("create_time");

        List<Message> messages = list(wrapper);
        return messages.stream().map(message -> {
            MessageDto dto = new MessageDto();
            BeanUtils.copyProperties(message, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Message> getRecentMessages(Long conversationId, int limit) {
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", conversationId)
                .orderByDesc("create_time")
                .last("LIMIT " + limit);

        List<Message> messages = list(wrapper);
        messages.sort((a, b) -> a.getCreateTime().compareTo(b.getCreateTime()));
        return messages;
    }
}